import { useEffect, useRef } from "react";
import * as THREE from "three";
import { CSS2DObject } from "three/addons/renderers/CSS2DRenderer.js";
import { lglt2xyz } from "../utils/lglt2xyz";
import { CSS2DRenderer } from "three/addons/renderers/CSS2DRenderer.js";
import { useThree, useFrame } from "@react-three/fiber";

const data = [
  {
    lng: 103.810906,
    lat: 30.410404,
    address: "新津区",
  },
];

export function Marker({ CSS2DRenderer }: { CSS2DRenderer: CSS2DRenderer }) {
  const GroupProps = useRef<THREE.Group | null>(null);
  const { camera, gl, scene } = useThree();
  const Info = ({
    name,
    position,
  }: {
    name: string;
    position: THREE.Vector3;
  }) => {
    const dom = document.createElement("div");
    dom.style.pointerEvents = 'auto'
    dom.addEventListener("click", () => {
      camera.lookAt(position);
      console.log(position);
    })
    dom.innerHTML = `<div class="name" style="padding:20px;background-color:#fff;border-radius:10px;"><span>${name}</span></div>`;
    return dom;
  };
  const createMarker = () => {
    const markers = data.map((item) => {
      const { x, y, z } = lglt2xyz(item.lng, item.lat, 30);
      const css2Obj = new CSS2DObject(
        Info({ name: item.address, position: new THREE.Vector3(x, y, z) })
      );
      css2Obj.position.set(x, y, z);
      return css2Obj;
    });
    markers.forEach((item) => {
      GroupProps.current?.add(item);

      console.log(item);
    });
  };
  useFrame(() => {
    CSS2DRenderer.render(scene, camera);
  });
  useEffect(() => {
    createMarker();
  }, []);
  return <group ref={GroupProps}></group>;
}
